// 定义子路由 
const express = require('express');
const mysql = require('mysql')
const pool = require("../db");
const Router = express.Router();

//用户注册 /reg
Router.post('/reg', (req, res, next) => {
	//获取post传递的参数
	console.log(req.body)
	var obj = req.body
	// 获取用户名和密码信息
	let useName = req.body.useName;
	let usePwd = req.body.usePwd;
	let phone = req.body.phone

	//以useName为条件进行查找操作，以保证用户名的唯一性
	let sql = 'SELECT COUNT(useName) AS count FROM user WHERE useName=?';
	pool.query(sql, [useName], (err, results) => {
		if (err) {
			//如果SQL中出现错误，交给下一个错误处理中间件
			//阻止往后执行
			return next(err)
		}
		console.log(results);
	  	let count = results[0].count;
	  	if (count == 0) {
			// 将用户的相关信息插入到数据表
			sql = 'insert into user(useName,usePwd,phone) values(?,?,?)';
			pool.query(sql, [useName,usePwd,phone], (error, results) => {
				if (err) {
					//如果SQL中出现错误，交给下一个错误处理中间件
					//阻止往后执行
					return next(err)
				}
				res.send({ code: 200, msg: '注册成功' })
			})
	  	} else {
			res.send({ code: 201, msg: '用户已存在'})
	  	}
	});
})


//用户登录 /login
Router.post('/login', (req, res, next) => {
	//获取post传递的参数
	console.log(req.body, '4')
	var obj = req.body
	console.log(obj, '5')
	//执行SQL命令，查询数据库中是否有用户名和密码同时满足的数据
	pool.query('select * from user where useName=? and usePwd=?', [obj.useName, obj.usePwd], (err, results) => {
		if (err) {
			//如果SQL中出现错误，交给下一个错误处理中间件123
			//阻止往后执行
			return next(err)
		}
		console.log(results, '123456')
		//结果是数组，如果是空数组登录失败,否则登录成功
		if (results.length === 0) {
			res.send({ code: 400, msg: '登录失败' })
		} else {
			res.send({ code: 200, msg: '登录成功' ,results:results[0]})
		}
	})
})

// 修改个人资料(不修改用户名时)
Router.post('/change',(req,res,next)=>{
	//获取post传递的参数
	let phone = req.body.phone
	let pic = req.body.pic
	let uid = req.body.uid
	pool.query('update user set phone=?,pic=? where user_id=?',[phone,pic,uid],(err,results)=>{
		if (err) {
			//如果SQL中出现错误，交给下一个错误处理中间件123
			//阻止往后执行
			return next(err)
		}
		if (results.affectedRows === 0) {
			res.send({ code: 201, msg: '修改失败' })
		} else {
			pool.query('select * from user where user_id=?',[uid],(err,results)=>{
				if (err) {
					return next(err)
				}
				console.log(results);
				res.send({ code: 200, msg: '修改成功',results:results})
			})
		}
	})
})

//修改个人资料(修改用户名时，要判断用户名是否存在)
Router.post('/changeAll',(req,res,next)=>{
	let useName = req.body.useName
	let phone = req.body.phone
	let pic = req.body.pic
	let uid = req.body.uid
	pool.query('select count(useName) as count from user where useName=?',[useName],(err,results)=>{
		if (err) {
			return next(err)
		}
		console.log(results);
		let count = results[0].count;
		console.log(count);
	  	if (count == 0) {
			  pool.query('update user set useName=?,phone=?,pic=? where user_id=?',[useName,phone,pic,uid],(err,results)=>{
				  if (err) {
					  return next(err)
				  }
				  if (results.affectedRows === 0) {
					  res.send({ code: 202, msg: '修改失败' })
				  } else {
					  pool.query('select * from user where user_id=?',[uid],(err,results)=>{
						  if (err) {
							  return next(err)
						  }
						  console.log(results);
						  res.send({ code: 200, msg: '修改成功',results:results})
					  })
				  }
			  })
		}else{
			res.send({ code: 201, msg: '用户名已存在',a:results})
		}
	})
})


// 修改头像
// 配置multer中间件
const multer = require('multer');
const uuid = require('uuid');
obj = multer.diskStorage({
  //设置上传后文件路径，upload文件夹会自动创建
  destination: function (req, file, cb) {
    //指定目录
    //cb ---> callback
    cb(null, 'upload');
  }, 
   //给上传文件重命名
  filename: function (req, file, cb) {
    // 指定文件名
    let name = file.originalname;
    // name:  abcd.jpg    xxxdfdd.zip
    let ext = name.substr(name.lastIndexOf('.'));
    cb(null, uuid.v4() + ext);
  },
});
const uploadTools = multer({
  storage: obj,
});


Router.post('/upload',
  uploadTools.array('uploadFile'),(req,res)=>{
    // console.log(req.files);
    // 这里创建一个空数组
    let urls = []
    // 循环拿到的路径
    req.files.forEach(item=>{
    //   console.log(item.filename);
      urls.push('http://localhost:3000/'+item.filename)
    })
    // 把路径返回
    res.send(urls)
  }),

// 查询头像
Router.get('/selectPic', (req, res, next) => {
	var pic = req.query.uid
	//执行SQL命令，查询数据库中是否有用户名和密码同时满足的数据
	pool.query('select pic from user where user_id=?', [pic], (err, results) => {
		if (err) {
			return next(err)
		}
		// console.log(results, '123456')
		//结果是数组，如果是空数组登录失败,否则登录成功
		if (results.length === 0) {
			res.send({ code: 400, msg: '失败' })
		} else {
			res.send({ code: 200, msg: '成功' ,results:results[0]})
		}
	})
})

module.exports = Router